package com.carmaintain.servlets;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.carmaintain.common.Constants;
import com.carmaintain.common.Utils;
import com.carmaintain.db.CommonLib;
import com.carmaintain.models.ResultObject;

/**
 * Servlet implementation class CheckApkVersion
 */
public class CheckApkVersion extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckApkVersion() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int currentVersion;
		ResultObject result = new ResultObject();

		try {
			request.setCharacterEncoding("UTF-8");
			if (!Utils.checkSign(request)) {
				result.setCode(Constants.CODE_SIGN_ERROR);
				result.setMessage(Constants.MESSAGE_WRONG_SIGN);
				response.setCharacterEncoding("UTF-8");
				response.getWriter().print(Utils.genJsonString(result));
				return;
			}
			if (Utils.empty(request.getParameter("current_version"))) {
				result.setCode(Constants.CODE_MISS_PARAMATER);
				result.setMessage(Constants.MESSAGE_MISS_PARAMATER);
				response.setCharacterEncoding("UTF-8");
				response.getWriter().print(Utils.genJsonString(result));
				return;
			} else {
				currentVersion = Integer.parseInt(request.getParameter("current_version"));
			}
		} catch (Exception e) {
			result.setCode(Constants.CODE_WRONG_PARAMATER);
			result.setMessage(Constants.MESSAGE_WRONG_PARAMATER);
			Utils.addTestMessage(result, e);
			response.setCharacterEncoding("UTF-8");
			response.getWriter().print(Utils.genJsonString(result));
			return;
		}
		
		try {
			Map<String, Object> dataMap = CommonLib.checkApkVersion(currentVersion);
			if (dataMap != null) {
				result.setCode(Constants.CODE_SUCCESS);
				result.setMessage(Constants.MESSAGE_SUCCESS);
				result.setResultData(dataMap);
			} else {
				result.setCode(Constants.CODE_FAIL);
				result.setMessage(Constants.MESSAGE_FAIL);
			}
		} catch (Exception e) {
			result.setCode(Constants.CODE_EXCEPTION);
			result.setMessage(Constants.MESSAGE_EXCETION);
			Utils.addTestMessage(result, e);
		}
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(Utils.genJsonString(result));
	}

}
